//
//  WZHCountDown.swift
//  ShiGuangJiaSwift
//
//  Created by 汪志浩 on 2022/10/9.
//

import Foundation
public class WZHCountDown {
    public var timer : DispatchSource?
    /**每秒走一次，回调block**/
    public func countDown(PER_SECClosure: (()->())?) {
        let queue: DispatchQueue = DispatchQueue.global()
        guard let t = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue) as? DispatchSource  else{return}
        
        timer = t
        // 每秒执行
        t.schedule(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(0), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
        t.setEventHandler { () -> Void in
            DispatchQueue.main.async(execute: { () -> Void in
                PER_SECClosure?()
            })
        }
        t.resume()
    }
    
    ///释放定时器
    public func destoryTimer(){
        guard let t = timer else {return}
        t.cancel()
        self.timer = nil
    }
}
